<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>总记录条数: 20条</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button v-allow="'eee'" type="warning" size="small" @click="$router.push('/import')">导入excel</el-button>
          <el-button type="danger" size="small" @click="hExportExcel">导出excel</el-button>
          <el-button type="primary" size="small" @click="xinzeng()">新增员工</el-button>
        </template>

      </PageTools>
      <el-card style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template slot-scope="scope">

              <ImageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式">
            <template slot-scope="scope">
              <!-- 转换为中文将1 -->
              {{ formatEmployment( scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />

          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="fenpei(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="shanchu(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->

        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :total="total"
            :page-size="pageParams.size"
            @current-change="hCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog title="新增员工" :visible.sync="showDialog">

        <Addor-edit v-if="showDialog" @close="guanbi" @update-empolyee="hUpdateEmpolyee" />
      </el-dialog>
      <el-dialog :visible.sync="show" :close-on-click-modal="false" :close-on-press-escape="false">
        <AssignRole v-if="show" :id="id" @close-dialog="guan" @close="hUpdateClose" /></el-dialog>
    </div>
  </div>
</template>
<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'// 导入梅举来转换
import AddorEdit from './empDialog'
import AssignRole from './assignRole'
const hireType = {}// 定义一个空对象
EmployeeEnum.hireType.forEach(item => { // 遍历id让value值等于id,
  hireType[item.id] = item.value
})
export default {

  name: 'Employees',
  components: {
    AddorEdit,
    AssignRole
  },
  data() {
    return {
      show: false, // 控制分配权限的出现
      showDialog: false, // 新增弹出层
      size: null, // 每页条数
      list: [], // 表格数据
      total: 0, // 总条目数
      pageParams: { // 分页
        page: 1, // 页码
        size: 5// 每页数据
      },
      id: ''// 传给子组件一个id
    }
  },
  created() {
    this.loadEmployeeList()// 获取表格数据
  },
  methods: {
    async loadEmployeeList() { // 获取表格数据
      try {
        const res = await getEmployeeList(this.pageParams)
        console.log('数据', res)
        this.list = res.data.rows
        this.total = res.data.total
        this.id = res.data.rows.id// 传给子组件id
      } catch (err) {
        console.log(err)
      }
    },

    formatEmployment(id) {
      // 对后端返回的类型的编码进行翻译 ，还原成 中文
      // 第一种方法
      // const rs = EmployeeEnum.hireType.find(item => item.id === id)
      return hireType[id]// 让回id值,就能在页面显示value的值
    },
    hCurrentChange(curPage) {
      this.pageParams.page = curPage// 将切换事件给页码
      this.loadEmployeeList()
    },
    async doDel(id) { // 删除员工
      try {
        const res = await delEmployee(id)
        console.log(res)
        this.$message.success('删除成功')
        if (this.list.length === 1) {
          this.pageParams.page--
        }
        if (this.pageParams.page <= 0) {
          this.pageParams.page = 1
        }
        this.loadEmployeeList()
      } catch (err) {
        console.log(err)
      }
    },
    shanchu(id) { // 删除事件
      console.log('1')
      this.$confirm('你确定要删除吗').then(() => {
        this.doDel(id)
      }).catch(() => {

      })
    },
    xinzeng() { // 新增
      this.showDialog = true// 打开弹窗
    },
    guanbi() { // 子传父关闭弹窗
      this.showDialog = false
    },
    hUpdateEmpolyee() { // 添加事件之后重新请求，关闭弹窗
      this.showDialog = false
      this.loadEmployeeList()// 获取表格数据
    },
    async  hExportExcel() { // 导出表格数据
      const res = await getEmployeeList(this.pageParams)// 拿到要导出的数据
      console.log('数据', res)
      const obj = this.transData(res.data.rows)
      import('@/vandor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
          header: obj.header, // 表头 必填
          data: obj.data, // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    transData(rows) {
      // 写代码
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }

      // 写代码
      // header => ['id', '手机号', '用户名', ... ]
      // data => [
      //   ["604f764971f93f3ac8f365c2", "13800000002", "管理员",.... ]
      // ]
      const enKeys = Object.keys(rows[0])
      // console.log(enKeys)//
      const header = enKeys.map(enKey => {
        return map[enKey]
        // console.log(header)
      })
      const data = rows.map(obj => {
        return Object.values(obj)
      })

      return { header, data }
    },
    fenpei(id) {
      this.show = true
      this.id = id
      console.log('当前要编辑的id是', id)
    },
    guan() {
      // 传给子组件取消按钮状态
      this.show = false
    },
    hUpdateClose() { // 发送成功后
      this.show = false// 关闭弹窗
      this.loadEmployeeList()
    }
  }

}

</script>
